package com.xiaoxiao.springbootstudy.controller;

import com.xiaoxiao.springbootstudy.pojo.Categroy;
import com.xiaoxiao.springbootstudy.pojo.vo.TreeVO;
import com.xiaoxiao.springbootstudy.service.CategroyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class CategoryController {
    @Autowired
    private CategroyService categroyService;

    @GetMapping("/categoryList")
    public List<TreeVO> categoryList() {
        return categroyService.queryCategoryListService();
    }

    @PostMapping("/saveCategory")
    public Map<String, Object> saveCategory(@RequestBody Categroy categroy) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "操作失败");
        try {
            categroyService.save(categroy);
            result.put("code", 200);
            result.put("msg", "保存商品类目成功");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;

    }

    @GetMapping("/loadCategory/{id}")
    public Categroy loadCategory(@PathVariable Integer id){
        return categroyService.getById(id);
    }

    @PostMapping("/updateCategory")
    public Map<String,Object> updateCategory(@RequestBody Categroy categrory){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败");
        try{
            categroyService.updateById(categrory);
            result.put("code",200);
            result.put("msg","更新商品类目成功");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    @GetMapping("/deleteCategory/{id}")
    public Map<String,Object> deleteCategory(@PathVariable Integer id){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败");
        try{
            categroyService.removeById(id);
            result.put("code",200);
            result.put("msg","删除商品类目成功");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
}
